package framework.utils;

import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;


/**
 * 项目名称：RenRenERP <br />
 * 类名称：CookieUtils <br />
 * 创建人：Administrator <br />
 * 备注： <br />
 * 
 * @version <br />
 */
public class CookieUtils
{
	private HttpServletRequest request;
	private HttpServletResponse response;

	private static final int EXPIRE_TIME = 60 * 60 * 24 * 365;

	public CookieUtils(HttpServletRequest request, HttpServletResponse response)
	{
		this.request = request;
		this.response = response;
	}

	/**
	 * 将value添加到Cookie
	 */
	public void addCookie(String name, String value)
	{
		try
		{
			Cookie cookies = new Cookie(name, URLEncoder.encode(value, CharsetUtils.UTF_8));
			cookies.setPath("/");
			cookies.setMaxAge(EXPIRE_TIME);

			response.addCookie(cookies);
		}
		catch (Exception e)
		{
		}
	}

	/**
	 * 根据名称从Cookie中取值
	 */
	public String getCookieValue(String cookieName)
	{
		if (StringUtils.isEmpty(cookieName))
			return StringUtils.EMPTY;

		try
		{
			Cookie cookie = getCookie(cookieName);
			if (cookie == null)
				return StringUtils.EMPTY;

			return URLDecoder.decode(cookie.getValue(), CharsetUtils.UTF_8);
		}
		catch (Exception e)
		{
			return StringUtils.EMPTY;
		}
	}

	/**
	 * 根据名称获取Cookie
	 */
	private Cookie getCookie(String cookieName)
	{
		Cookie[] cookies = request.getCookies();
		if (ArrayUtils.isEmpty(cookies))
			return null;

		for (int i = 0; i < cookies.length; i++)
		{
			Cookie cookie = cookies[i];
			if (cookie.getName().equals(cookieName))
				return cookie;
		}

		return null;
	}

	/**
	 * 根据名称删除Cookie
	 */
	public boolean deleteCookie(String cookieName)
	{
		if (StringUtils.isEmpty(cookieName))
			return false;

		Cookie cookie = getCookie(cookieName);
		if (cookie == null)
			return false;

		cookie.setPath("/"); // 不要漏掉
		cookie.setMaxAge(0); // 如果0，就说明立即删除
		response.addCookie(cookie);

		return true;
	}
}
